﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SN.Core;
using SN.Data;
using Agro.Models;
using System.Web;
using System.IO;

namespace Agro.Services
{
    public class FileService : BaseService, IFileService
    {
        public DataTable FileGetList(QueryBase query, WhereClip wclip)
        {
            var section = DB.From<T_File>().Where(wclip);
            var dt = section.ToTablePage(query);
            return dt;
        }
        public List<T_File> GetTopFileList(int topsize)
        {
            List<T_File> dt = (List<T_File>)DB.From<T_File>().OrderBy(T_File._.File_ID.Desc).GetTop(topsize).ToList();
            return dt;
        }
        public bool FileSave(T_File File, out string Msg)
        {
            Msg = string.Empty;
            try
            {
                DB.Save<T_File>(File);
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
                return false;
            }

            return true;
        }

        public bool DeleteFile(string ids, out string msg)
        {
            msg = string.Empty;
            string[] id = ids.Split(',');

            foreach (var item in id)
            {//先删除数据库数据，再删文件，因为数据库数据可以rollback,当文件删除失败时，rollback，保证数据不丢失
                using (DbTrans trans = DB.BeginTrans())
                {
                    try
                    {
                        T_File file = GetEntity<T_File>(T_File._.File_ID == item);
                        trans.Delete<T_File>(T_File._.File_ID == item);
                        
                        string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/" + file.File_ServerName);
                        File.Delete(filePath);
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        msg = ex.Message;
                        return false;
                    }

                }
            }
           
            return true;
        }

    }
}
